//
//  SSWelcomeViewController.swift
//  MyMicroBlog
//
//  Created by stevenSu on 15/7/30.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit
import SDWebImage

private let avatarViewSize: CGFloat = 90
private let avatarViewStartMargin: CGFloat = 160
private let welcomeLabelMargin: CGFloat = 16
let SSWelcomeViewControllerMaxCacheAge = 3600 * 24
let SSWelcomeViewControllerAnimationDuration = 2.0
let SSWelcomeViewControllerSpringDamping: CGFloat = 0.8
let SSWelcomeViewControllerSpringVelocity: CGFloat = 5.0

class SSWelcomeViewController: UIViewController {
    private var avatarBottomCons: NSLayoutConstraint?
    private lazy var backgroundView: UIImageView = UIImageView(image: UIImage(named: "ad_background"))
    private lazy var avatarView: UIImageView = {
        let imgView = UIImageView(image: UIImage(named: "avatar_default_big"))
        imgView.layer.cornerRadius = avatarViewSize * 0.5
        imgView.layer.masksToBounds = true
        return imgView
    }()
    private lazy var welcomeLabel: UILabel = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        SDWebImageManager.sharedManager().imageCache.maxCacheAge = SSWelcomeViewControllerMaxCacheAge
        if let userToken = SSUserToken.loadToken() {

            userToken.userInfo.loadUserInfo({ (result, error) -> () in
                
                if error != nil {
                    print(error)
                    return
                }
                
                // 下载图片，本地有会优先从本地取
                if userToken.userInfo.avatar_large != nil {
                    SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: userToken.userInfo.avatar_large!)!, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) -> Void in
                        self.avatarView.image = image
                        userToken.userInfo.avatar_large_image = image
                    })
                }
                
                if userToken.userInfo.name != nil {
                    self.welcomeLabel.text = "欢迎回来,\(userToken.userInfo.name!)"
                }
            })
        }
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        avatarBottomCons!.constant = view.bounds.height - avatarBottomCons!.constant
        UIView.animateWithDuration(SSWelcomeViewControllerAnimationDuration, delay: 0, usingSpringWithDamping: SSWelcomeViewControllerSpringDamping, initialSpringVelocity: SSWelcomeViewControllerSpringVelocity, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            self.view.layoutIfNeeded()
            }) { (_) -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName(SSRootControllerSwitchNotification, object: true)
        }
    }
    
    private func setupUI() {
        view.addSubview(backgroundView)
        view.addSubview(avatarView)
        view.addSubview(welcomeLabel)
        
        backgroundView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": backgroundView]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": backgroundView]))
        
        avatarView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraint(NSLayoutConstraint(item: avatarView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: avatarView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: avatarViewSize))
        view.addConstraint(NSLayoutConstraint(item: avatarView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: avatarViewSize))
        view.addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: avatarView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: avatarViewStartMargin))
        avatarBottomCons = view.constraints.last
        
        welcomeLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraint(NSLayoutConstraint(item: welcomeLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: avatarView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: welcomeLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: avatarView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: welcomeLabelMargin))
    }

}
